<template>
    <div class="app-container" v-loading="pageLoading">
        <div align="center">
            <el-button-group>
                <el-button type="primary" size="small" :plain="tableType !== 'gameManage'" @click="selectTabletype('gameManage')">游戏管理</el-button>
                <el-button type="primary" size="small" :plain="tableType !== 'channelManage'" @click="selectTabletype('channelManage')">渠道管理</el-button>
            </el-button-group>
        </div>
        <el-card style="margin-top:30px">
            <el-input style="margin: 8px 8px;width:30%;min-width:300px" placeholder="请输入游戏或渠道名" v-model="keyWord" class="input-with-select " @keyup.enter.native="searchList">
                <el-button slot="append" icon="el-icon-search" @click="searchList"></el-button>
            </el-input>
            <el-table :data="currentTableData" style="width: 100%" border>
                <el-table-column v-for="item in tableData.fields" :key="item.prop" :prop="item.prop" :label="item.label" align="center" :sortable="item.label == '操作' ? false : true">
                    <!-- table-header-->
                    <template slot="header" slot-scope="scope">
                        <el-button v-if="item.label == '操作'" type="success" size="small" @click="handleAdd(scope)">
                            新增
                        </el-button>
                        <span v-else-if="item.label == 'icon'">
                            ICON
                        </span>
                        <span v-else>{{ item.label }}</span>
                    </template>
                    <!-- table-body-->
                    <template slot-scope="scope">
                        <template v-if="item.label == '操作'">
                            <el-button type="primary" size="small" @click="handleEdit(scope)">
                                修改
                            </el-button>
                            <el-button type="danger" size="small" @click="handleDelete(scope)">
                                删除
                            </el-button>
                        </template>
                        <template v-else-if="item.prop == 'iconUrl'" class="demo-image__preview">
                            <div style="width:60px; height: 60px;margin:0 auto;display: flex;align-items: center;justify-content: center;">
                                <el-image fill="contain" :src="scope.row.iconUrl" :preview-src-list="[scope.row.iconUrl]"></el-image>
                            </div>
                        </template>
                        <span v-else>{{ scope.row[item.prop] }}</span>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageInfo.currentPage" :page-sizes="pageInfo.pageSizeList" :page-size="pageInfo.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="tableData.data.length" align="center" style="padding-top:10px">
            </el-pagination>
        </el-card>
        <el-dialog v-if="dialogShow" :title="dialogType === 'edit' ? '修改' : '新增'" :visible.sync="dialogVisible" width="30%" :close-on-click-modal="false" @open="setFormRules" @closed="resetForm">
            <div v-loading="loading">
                <el-form ref="gameForm" :model="tableForm" :rules="tableRules" label-width="100px">
                    <template v-if="tableType == 'gameManage'">
                        <!-- <el-form-item label="平台" prop="platform">
                            <el-select v-model="tableForm.platform" placeholder="请选择平台" style="width: 100%;">
                                <el-option label="安卓" value="Android"></el-option>
                                <el-option label="小游戏" value="H5"></el-option>
                                <el-option label="IOS" value="IOS"></el-option>
                            </el-select>
                        </el-form-item> -->
                        <el-form-item label="游戏名称" prop="gameName">
                            <el-input v-model="tableForm.gameName" placeholder="请输入游戏名称"></el-input>
                        </el-form-item>
                        <el-form-item label="游戏Code" prop="gameCode">
                            <el-input v-model="tableForm.gameCode" placeholder="请输入游戏Code" :readonly="dialogType === 'edit' ? true : false "></el-input>
                        </el-form-item>
                        <el-form-item label="游戏icon" prop="iconUrl">
                            <el-upload class="avatar-uploader " :action="uploadAddress" :before-upload="beforeAvatarUpload" :on-error="uploadErr" :headers="{
                            Authorization:'Bearer '+token,
                        }" :show-file-list="false" :on-success="imageUpload" list-type="picture-card">
                                <img v-if="tableForm.iconUrl" :src="tableForm.iconUrl" style="width: 100%;height: 100%;">
                                <i v-else class="el-icon-plus "></i>
                            </el-upload>
                        </el-form-item>
                    </template>
                    <template v-else="tableType == 'channelManage'">
                        <el-form-item label="平台" prop="platform">
                            <el-select v-model="tableForm.platform" placeholder="请选择平台" style="width: 100%;">
                                <el-option label="安卓" value="Android"></el-option>
                                <el-option label="小游戏" value="H5"></el-option>
                                <el-option label="IOS" value="IOS"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="COP渠道ID" prop="copChannelId">
                            <el-input v-model="tableForm.copChannelId" placeholder="请输入COP渠道ID" :readonly="dialogType === 'edit' ? true : false "></el-input>
                        </el-form-item>
                        <el-form-item label="渠道名称" prop="channelName">
                            <el-input v-model="tableForm.channelName" placeholder="请输入渠道称"></el-input>
                        </el-form-item>
                    </template>
                </el-form>
            </div>
            <div slot="footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="onSubmit" :loading="submitLoading">确 定</el-button>
            </div>
        </el-dialog>
        <back-to-top />
    </div>
</template>



<script >
import { getAuthGameList, addGame, updateGameList, delGame, getChannelList, addChannel, updateChannelList, delChannel } from "@/api/game";
import { mapGetters } from "vuex";
import { deepClone } from "@/utils";
import BackToTop from "@/components/BackToTop"
import { parseToFileUrl } from "@/filters/index"
export default {
    name: 'ConfigIndex',
    components: {
        BackToTop
    },
    data () {
        return {
            pageLoading: false,
            loading: false,
            submitLoading: false,
            tableType: "gameManage",
            tableForm: {},
            tableData: {
                data: [],
                fields: [],
            },
            pageInfo: {
                currentPage: 1,
                pageSizeList: [20, 30, 40, 50],
                pageSize: 50,
            },
            gameManageFrom: {
                id: "",
                platform: "",
                gameName: "",
                gameCode: "",
                iconId: "",
                iconUrl: "",
                createUserName: "",
                createTime: "",
                updateUserName: "",
            },
            channelManageFrom: {
                id: "",
                copChannelId: "",
                channelName: "",
                platform: "",
            },
            dialogVisible: false,
            dialogType: "add",
            imagesInfo: {},
            uploadAddress: process.env.VUE_APP_BASE_API + "api/file/upload",
            tableRules: {},
            dialogShow: true,
            keyWord: '',
            tableDataSearch: [],
        }
    },
    computed: {
        ...mapGetters(["token"]),
        currentTableData () {
            const { currentPage, pageSize } = this.pageInfo
            return this.tableData.data.slice((currentPage - 1) * pageSize, currentPage * pageSize)
        }
    },
    mounted () {
        this.getAjax()
    },
    methods: {
        //分页
        handleSizeChange (pageSize) {
            this.pageInfo.pageSize = pageSize
        },
        handleCurrentChange (currentPage) {
            this.pageInfo.currentPage = currentPage
        },

        selectTabletype (type) {
            this.keyWord = null
            this.tableType = type
            this.setNewForm()
            this.getAjax()
        },
        setNewForm () {
            switch (this.tableType) {
                case "gameManage":
                    this.tableForm = JSON.parse(JSON.stringify(this.gameManageFrom))
                    break
                case "channelManage":
                    this.tableForm = JSON.parse(JSON.stringify(this.channelManageFrom))
                    break
            }
        },
        async getAjax () {
            this.pageLoading = true
            let res = []
            let data = []
            try {
                switch (this.tableType) {
                    case "gameManage":
                        res = await getAuthGameList()
                        res.data = res.data || []
                        res.data = res.data.map(r => {
                            r.iconUrl = r.iconUrl ? parseToFileUrl(r.iconUrl) : require("@/assets/404_images/404.png")
                            return r
                        })
                        this.tableData.fields = [
                            { prop: "iconUrl", label: "icon" },
                            { prop: "gameId", label: "AppId" },
                            { prop: "gameName", label: "游戏名" },
                            { prop: "gameCode", label: "游戏Code" },
                            // { prop: "platform", label: "平台" },
                            { prop: "createUserName", label: "创建用户" },
                            { prop: "createTime", label: "创建时间" },
                            { prop: "updateUserName", label: "更新用户" },
                            { label: "操作" },
                        ]
                        break
                    case "channelManage":
                        res = await getChannelList()
                        this.tableData.fields = [
                            { prop: "id", label: "ID" },
                            { prop: "copChannelId", label: "COP渠道ID" },
                            { prop: "channelName", label: "渠道名称" },
                            { prop: "platform", label: "平台" },
                            { label: "操作" },
                        ]
                        break
                }

                data = res.data ? res.data : []
                this.tableData.data = JSON.parse(JSON.stringify(data))
                this.tableDataSearch = JSON.parse(JSON.stringify(data))
                this.pageLoading = false;
            } catch (err) {
                console.log(err);
                this.pageLoading = false;
            }
        },
        async addAjax (params) {
            this.submitLoading = true
            try {
                switch (this.tableType) {
                    case "gameManage":
                        await addGame(params)
                        break
                    case "channelManage":
                        await addChannel(params)
                        break
                }
                this.$message({
                    type: "success",
                    message: "添加成功"
                })
                await this.getAjax()
                this.submitLoading = false
                this.dialogVisible = false
            } catch (error) {
                console.log(error);
                this.submitLoading = false
            }
        },
        async updateAjax (params) {
            this.submitLoading = true
            console.log(params)
            try {
                switch (this.tableType) {
                    case "gameManage":
                        await updateGameList(params)
                        break
                    case "channelManage":
                        await updateChannelList(params)
                        break
                }
                this.$message({
                    type: "success",
                    message: "修改成功"
                })
                await this.getAjax()
                this.dialogVisible = false
            } catch (error) {
                console.log(error);
                ("修改失败！");
            }
            this.submitLoading = false
        },
        async delAjax (params) {
            this.submitLoading = true
            try {
                switch (this.tableType) {
                    case "gameManage":
                        await delGame(params)
                        break
                    case "channelManage":
                        await delChannel(params)
                        break
                }
                this.$message({
                    type: "success",
                    message: "删除成功"
                })
                await this.getAjax()
                this.submitLoading = false
            } catch (e) {
                this.submitLoading = false
                //TODO handle the exception
            }

        },
        handleAdd () {
            this.setNewForm()
            this.dialogType = "add"
            this.dialogVisible = true
        },
        handleEdit (scope) {
            this.tableForm = JSON.parse(JSON.stringify(scope.row))
            this.dialogType = "edit"
            this.dialogVisible = true
        },
        setFormRules () {
            switch (this.tableType) {
                case 'gameManage':
                    this.tableRules = {
                        platform: [{ required: true, message: "请选择平台", trigger: "blur" }],
                        gameName: [{ required: true, message: "请输入游戏名", trigger: "blur" }],
                        gameCode: [{ required: true, message: "请输入游戏Code（表名后缀，如83ylljlm）", trigger: "blur" }],
                        iconId: [{ required: true, message: "请上传icon", trigger: "blur" }],
                        iconUrl: [{ required: true, message: "请上传icon", trigger: "blur" }],
                    }
                    break
                case 'channelManage':
                    this.tableRules = {
                        platform: [{ required: true, message: "请选择平台", trigger: "blur" }],
                        channelName: [{ required: true, message: "请输入渠道名", trigger: "blur" }],
                        copChannelId: [{ required: true, message: "请输入COP渠道ID", trigger: "blur" }]
                    }
                    break
            }

        },
        resetForm () {
            this.dialogShow = false
            this.$nextTick(() => {
                this.dialogShow = true
            })
        },
        handleDelete (scope) {
            this.$confirm("确认删除?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    let params = {}
                    switch (this.tableType) {
                        case 'channelManage':
                            params = {
                                id: scope.row.id
                            }
                            break
                        case 'gameManage':
                            params = {
                                id: scope.row.gameId
                            }
                            break

                    }
                    this.delAjax(params)
                })
                .catch(() => { });
        },
        imageUpload (res) {
            this.imagesInfo = res.data ? deepClone(res.data) : {};
            this.tableForm.iconUrl = this.imagesInfo.url;
            this.tableForm.iconId = this.imagesInfo.id;
        },
        beforeAvatarUpload (file) {
            let isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
            let isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        uploadErr (err) {
            this.$message.error(err);
        },
        //搜索
        searchList () {
            let keyWord = this.keyWord;
            switch (this.tableType) {
                case 'gameManage':
                    this.tableData.data = this.tableDataSearch.filter(
                        (route) => route.gameName.indexOf(keyWord) != -1
                    );
                    break
                case 'channelManage':
                    this.tableData.data = this.tableDataSearch.filter(
                        (route) => route.channelName.indexOf(keyWord) != -1
                    );
                    break
            }
        },
        onSubmit () {
            this.$refs.gameForm.validate(async (valid) => {
                if (valid) {
                    this.submitLoading = true;
                    let params = {}
                    console.log(this.tableType)
                    switch (this.tableType) {
                        case 'gameManage':
                            params = {
                                id: this.tableForm.gameId,
                                gameName: this.tableForm.gameName,
                                iconId: this.tableForm.iconId,
                                iconUrl: this.tableForm.iconUrl,
                                gameCode: this.tableForm.gameCode,
                            }
                            break
                        case 'channelManage':
                            params = {
                                id: this.tableForm.id,
                                copChannelId: this.tableForm.copChannelId,
                                channelName: this.tableForm.channelName,
                                platform: this.tableForm.platform,
                            }
                            break
                    }
                    if (this.dialogType === "edit") {
                        this.updateAjax(params)
                    } else if (this.dialogType === "add") {
                        this.addAjax(params)
                    }
                }
            })
        },
    },
};
</script>
<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}
</style>
